<?php
require_once 'php-sdk/facebook.php' ;
require_once 'php-sdk/base_facebook.php' ;
require_once "gameAPI.php";
//connect_fb();
//$user = "100000861563120";//to be replaced by /me

//$user_id = facebook_api_call("/me?fields=id,name");
//$friendlist = get_friend_list($user_id["id"]);

//$factory_id = get_factory($user_id["id"]);

//$user_id = facebook_api_call("/".$user."?fields=id,name");
//initialize();
$user_id = get_user_id();
$friendlist = get_friend_list(array('user_id'=>$user_id));

$factory_id = get_factory_id($user_id);
$supervisors = get_certain_workers($factory_id, 'Supervisor');
$office_workers = get_certain_workers($factory_id, 'Office worker');
$production_workers = get_certain_workers($factory_id, 'Production line worker');
?>


<html>
<head>
<script src="js/jquery.js">
</script>
<script src="js/paginator.js">
</script>
<script>  
$(function(){ $("#friends").pagination(); }); 
</script>  
<style type="text/css">
body {
  background: url("images/play_screen.jpg") no-repeat;
}
.friendlist{
  position: absolute;
  font-family:"Arial";
  top: 130px;
  left: 60px;
  width: 180px;
  height: 700px;
  overflow: auto;
}
.supervisor{
  position: absolute;
  top: 150px;
  left: 307px;
  width: 210px;
  height: 125px;
}
.production{
  position: absolute;
  top: 520px;
  left: 307px;
  width: 210px;
  height: 125px;
}
.office{
  position: absolute;
  top: 330px;
  left: 307px;
  width: 210px;
  height: 125px;
}
.bottom_buttons{
  position: absolute;
  top: 700px;
  left: 287px;
  width: 510px;
  height: 125px;
}
.top_buttons{
  position: absolute;
  top: 40px;
  left: 287px;
  width: 200px;
  height: 200px;
}
.paginator{
  position: absolute;
  top: 700px;
  left: 80px;
  width: 200px;
  height: 200px;
}
</style>
<script language="javascript">

var free = new Array();
free["supervisor"] = <?php echo $free_slots["Supervisor"] ?>;
free["office"] = <?php echo $free_slots["Office worker"] ?>;
free["production"] = <?php echo $free_slots["Production line worker"] ?>;

function AddToFactory(dropdown)
{
	var myindex  = dropdown.selectedIndex;
    var SelValue = dropdown.options[myindex].value;
	var user_id = dropdown.name.substring(8);
	var x = document.getElementById(SelValue);
	x.src = "https://graph.facebook.com/"+user_id+"/picture";
	x.id = user_id;
	x.name = SelValue;
	free[SelValue]--;
	if (free[SelValue]==0)
	{
		var d1 = document.getElementsByTagName('select');
		for (var i=0; i< d1.length; i++)
		{
			for(var j=0;j<d1[i].options.length;j++)
			{
				if (d1[i].options[j].value == SelValue)
					d1[i].remove(j);
			}
		}
	}
}

function RemoveFromFactory(type)
{
	var x = document.getElementById(type);
	
	if (x)
	{
		x.src = "http://107.20.229.155/sqwtest/images/blank_profile_picture_small.jpg";
		x.id = x.name;
	
		var y = document.getElementById('jobtype_'+type.toString());
		y.selectedIndex = 0;
	
		var previous = free[x.name];
		free[x.name]++;
		if (previous == 0 && free[x.name] == 1)
		{
			var optn = document.createElement("OPTION");
			if (x.name=='production')
				text = "Production worker";
			else if (x.name=='office')
				text = "Office worker";
			else
				text = "Supervisor";
			optn.text = text;
			optn.value = x.name;
			
			var d1 = document.getElementsByTagName('select');
			
			for (var i=0; i<d1.length; i++)
			{
				d1[i].options.add(optn);
			}
		}
	}
	else
	{
		var string = "gameAPI.php?func=remove_friend_from_factory&factory_id=<?php echo $factory_id ?>&worker_id="+type;
		alert(string);
		window.location.href=string;
	}
}

function CancelAllSelections()
{
	var dropdowns = document.getElementsByTagName('select');

	for(var i=0; i<dropdowns.length; i++)
	{
		if(dropdowns[i].selectedIndex!=0)
		{
			var user_id = dropdowns[i].name.substring(8);
			RemoveFromFactory(user_id);
		}
	}
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}


/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 * 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json(arr) {
    var parts = [];
    //var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
	var is_list = false;

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}

function ConfirmSelection()
{
	var allPictures = document.getElementsByTagName('img');
	var notNew = ["supervisor","alreadysupervisor","production","alreadyproduction","office","alreadyoffice", "submitselection"];
	var allNewStaff = '';
	
	for(var i=0; i<allPictures.length;i++)
	{
		if (allPictures[i].id!='' && !inArray(allPictures[i].id, notNew))
		{
			allNewStaff = allNewStaff + allPictures[i].id + "=" + allPictures[i].name + "&";
		}
	}
	
	var string = "gameAPI.php?func=insert_friends_into_factory&factory_id=<?php echo $factory_id ?>&"+allNewStaff;
	alert(string);
	window.location.href=string;

	/*var json = JSON.stringify(allNewStaff);
	alert(json);
	$.ajax({
		type: "POST",
		url: "addfriends.php",
		data:  "data1":json,
		success: function(){
			alert( "huat ah!" );
   }
	});
	
	/*var http_request = new XMLHttpRequest();
	http_request.open("GET", "addfriends.php", true);
	http_request.onreadystatechange = function ()
	{
		if (http_request.readyState == done && http_request.status == ok) {
			http_request.responseText = json;
		}
	}
	http_request.send();*/

}

function showResult(str)
{
if (str.length==0)
  { 
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText['uid'];
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","gameAPI.php?func=get_friend_list&user_id=<?php echo $user_id ?>&q="+str,true);
xmlhttp.send();
}

</script>
</head>
<body>
<div id="search" class="search">
<form>
<input type="text" size="30" onkeyup="showResult(this.value)" />
</form>
<div id="livesearch"></div>
</div>
<div id="friends" class="friendlist">
<?php foreach($friendlist as $friend) : ?>
<p>
<img src="https://graph.facebook.com/<?php echo $friend["uid"] ?>/picture" /><a href="<?php echo $friend["profile_url"]?>"><?php echo $friend["name"]?></a><form action="">
				     <select id = "jobtype_<?php echo $friend["uid"] ?>" name="jobtype_<?php echo $friend["uid"] ?>" onchange="AddToFactory(this.form.jobtype_<?php echo $friend["uid"]?>)">
					 <option value="pleaseselect">Please Select</option>
					 <?php if ($free_slots["Supervisor"] != 0): ?> <option value="supervisor">Supervisor</option> <?php endif ?>
					 <?php if ($free_slots["Office worker"] !=0): ?> <option value="office">Office worker</option> <?php endif ?>
					 <?php if ($free_slots["Production line worker"] != 0): ?> <option value="production">Production worker</option><?php endif ?></form>
</p>
<?php endforeach; ?>
</div>
<div class="supervisor">
<table><tr>
<?php foreach($supervisors as $supervisor) : ?>
<td><?php if ($supervisor == -1): ?>
	<img id="supervisor" src="http://107.20.229.155/sqwtest/images/blank_profile_picture_small.jpg" onclick="RemoveFromFactory(this.id)">
	<?php else: ?>
	<img id="alreadysupervisor" name=<?php echo $supervisor ?> src="https://graph.facebook.com/<?php echo $supervisor ?>/picture" onclick="RemoveFromFactory(<?php echo $supervisor ?>)" />
	<?php endif ?>
</td>
<?php endforeach; ?>
</tr></table>
</div>
<div class="office">
<table><tr>
<?php foreach($office_workers as $ow) : ?>
<td><?php if ($ow == -1): ?>
	<img id="office" src="http://107.20.229.155/sqwtest/images/blank_profile_picture_small.jpg" onclick="RemoveFromFactory(this.id)">
	<?php else: ?>
	<img id="alreadyoffice" name=<?php echo $ow ?> src="https://graph.facebook.com/<?php echo $ow ?>/picture" onclick="RemoveFromFactory(<?php echo $ow ?>)" />
	<?php endif ?>
</td>
<?php endforeach; ?>
</tr></table>
</div>
<div class="production">
<table><tr>
<?php foreach($production_workers as $pw) : ?>
<td><?php if ($pw == -1): ?>
	<img id="production" src="http://107.20.229.155/sqwtest/images/blank_profile_picture_small.jpg" onclick="RemoveFromFactory(this.id)">
	<?php else: ?>
	<img id="alreadyproduction" name=<?php echo $pw ?> src="https://graph.facebook.com/<?php echo $pw ?>/picture" onclick="RemoveFromFactory(<?php echo $pw ?>)" />
	<?php endif ?>
</td>
<?php endforeach; ?>
</tr></table>
</div>
<div class="top_buttons">
<table><tr><td>
<img src="images/play_screen/back_.png" onmousedown="this.src='images/play_screen/back_click.png'; window.location.href='index.php';" onmouseover="this.src='images/play_screen/back_over.png';" onmouseout="this.src='images/play_screen/back_.png';" onmouseup="this.src='images/play_screen/back_over.png';" />
</td>
<td>
<img src="images/play_screen/cashin_.png" onmousedown="this.src='images/play_screen/cashin_click.png'; window.location.href='update_call.php'; window.location.href='index.php';" onmouseover="this.src='images/play_screen/cashin_over.png';" onmouseout="this.src='images/play_screen/cashin_.png';" onmouseup="this.src='images/play_screen/cashin_over.png';" />
</td>
<td>
<img src="images/play_screen/upgrade_.png" onmousedown="this.src='images/play_screen/upgrade_click.png';" onmouseover="this.src='images/play_screen/upgrade_over.png';" onmouseout="this.src='images/play_screen/upgrade_.png';" onmouseup="this.src='images/play_screen/upgrade_over.png';" />
</td>
</tr></table>
</div>
<div class="bottom_buttons">
<table><tr><td>
<img id="submitselection" src="images/play_screen/confirm_.png" onmousedown="this.src='images/play_screen/confirm_click.png'; ConfirmSelection();" onmouseover="this.src='images/play_screen/confirm_over.png';" onmouseout="this.src='images/play_screen/confirm_.png';" onmouseup="this.src='images/play_screen/confirm_over.png';"/>
</td>
<td>
<img src="images/play_screen/cancel_.png" onmousedown="this.src='images/play_screen/cancel_click.png'; CancelAllSelections();" onmouseover="this.src='images/play_screen/cancel_over.png';" onmouseout="this.src='images/play_screen/cancel_.png';" onmouseup="this.src='images/play_screen/cancel_over.png';" />
</td></tr></table>
</div>
</body>
</html>